import { reactive, ref, toRefs } from 'vue'
import { useHomeStore } from '@/store/home'
import { Params } from '@/types/home'

export const useHomeEffect = () => {
  const homeStore = useHomeStore()

  // 缓存置空
  const restStorage = () => {
    localStorage.setItem('home_filter_community_id', '')
    localStorage.setItem('home_filter_community', '')
    localStorage.setItem('home_filter_mch_id', '')
    localStorage.setItem('home_filter_mch', '')
    localStorage.setItem('home_filter_confirm_status', '')
    localStorage.setItem('home_filter_isolate_reason', '')
    localStorage.setItem('home_filter_isolate_status', '')
    localStorage.setItem('home_filter_isolate_endtime', '')
  }

  // 初始化置空
  restStorage()

  const payload = reactive({
    community: '全部社区',
    mch: '全部村/小区',
    community_id: '',
    mch_id: ''
  })

  const getStatistics = async () => {
    pageState.loading = true
    const { community_id, mch_id } = payload
    const params:Params = {}
    if (community_id) params.community_id = community_id
    if (mch_id) params.mch_id = mch_id
    
    homeStore.getStatistics(params).then((data) => {
      pageState.loading = false
    })
    .catch(() => {
      pageState.loading = false
    })
  }

  const handleSetCommunityTxt = (data: Params) => {
    const { community, community_id } = data
    payload.community = community as string
    payload.community_id = community_id as string
    localStorage.setItem('home_filter_community_id', community_id as string)
    localStorage.setItem('home_filter_community', community as string)
    getStatistics()
  }
  const handleSetCommunityChildTxt = (data: Params) => {
    const { mch, mch_id } = data
    payload.mch = mch as string
    payload.mch_id = mch_id as string
    localStorage.setItem('home_filter_mch_id', mch_id as string)
    localStorage.setItem('home_filter_mch', mch as string)
    getStatistics()
  }

  const pageState = reactive({
    loading: false,
    refreshing: false
  })

  const onrefresh = () => {
    setTimeout(() => {   
      payload.community = '全部社区'
      payload. mch = '全部村/小区'
      payload.community_id =  ''
      payload.mch_id =  ''
      restStorage()
      getStatistics()      
      pageState.refreshing = false 
   }, 1000) 
  }

  return {
    ...toRefs(payload),
    getStatistics,
    handleSetCommunityTxt,
    handleSetCommunityChildTxt,
    ...toRefs(pageState),
    onrefresh,
  }
}
